package com.miguo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.miguo.activity.base.BaseActivity;
import com.miguo.adapter.SearchKeyAdapter;
import com.miguo.app.AppConfig;
import com.miguo.app.AppContext;
import com.miguo.app.AppHelper;
import com.miguo.bean.CommentBean;
import com.miguo.bean.SearchKeyBean;
import com.miguo.component.search.SearchBarView;
import com.miguo.component.search.SearchContentView;
import com.miguo.framework.component.BaseStatusView;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.request.RequestJsonHandler;
import com.miguo.framework.utils.Toast;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.plugins.alibaba.BaiChuan;
import com.miguo.ui.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.View.OVER_SCROLL_NEVER;
import static android.view.View.OnClickListener;

public class SearchActivity extends BaseActivity implements AdapterView.OnItemClickListener, OnClickListener {

    private Context mContext;
    private ListView mMatchList;
    private SearchBarView mSearchBar;
    private SearchContentView mSearchContent;

    private List<SearchKeyBean> KeywordList;
    private SearchKeyAdapter KeywordAdapter;
    private boolean IntentState = false;
    private String keywords, mIntentkeyword;

    private RelativeLayout mContent;
    private BaseStatusView BaseStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mContext = this;
        findViewId();
        initView();
    }

    private void findViewId() {
        mSearchBar = (SearchBarView) findViewById(R.id.search_bar);
        mContent = (RelativeLayout) findViewById(R.id.content_view);

        mSearchContent = (SearchContentView) findViewById(R.id.search_content_view);
        BaseStatus = (BaseStatusView) findViewById(R.id.base_status_view);
        BaseStatus.setContentView(mContent);
        BaseStatus.getRefreshView().setOnClickListener(this);
        BaseStatus.getNetworkView().setOnClickListener(this);

        mMatchList = (ListView) findViewById(R.id.match_list);
        Intent intent = getIntent();
        if (null != intent && intent.hasExtra("keyWord")) {
            IntentState = true;
            mIntentkeyword = intent.getStringExtra("keyWord");
            mSearchBar.setHint(mIntentkeyword);
            mSearchBar.getEditText().setCursorVisible(false);
        }
    }

    private void initView() {
        // 设置软键盘不自动打开
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        KeywordList = new ArrayList<SearchKeyBean>();
        KeywordAdapter = new SearchKeyAdapter(this);
        mMatchList.setAdapter(KeywordAdapter);
        mMatchList.setOnItemClickListener(this);
        if (Build.VERSION.SDK_INT >= 9) {
            mMatchList.setOverScrollMode(OVER_SCROLL_NEVER);
        }

        mSearchBar.setBackListener(mBackListener);
        mSearchBar.setDeleteListener(mDeleteListener);
        mSearchBar.setSearchChangedListener(mSearchChangedListener);
        mSearchBar.setSearchListener(mSearchListener);
        mSearchBar.setSearchBtnListener(mSearchBtnListener);
    }


    private void getKeywords() {
        RequestJsonHandler handler = new RequestJsonHandler() {
            @Override
            public void onRequestFinish(JsonData json) {
                if (json.optInt("status") == 200) {
                    JsonData data = json.optJson("data");
                    KeywordList = CommentBean.SearchKey(data);
                    if (KeywordList != null && KeywordList.size() > 0) {
                        KeywordAdapter.addAll(KeywordList, true);
                        KeywordList.clear();
                    }
                    BaseStatus.setRefreshVisibility(View.GONE);
                }
            }

            @Override
            public void onRequestFail(FailData data) {
                BaseStatus.setRefreshVisibility(View.VISIBLE);
            }
        };
        Map<String, String> param = new HashMap<String, String>();
        param.put("k", keywords);
        HttpClient.post(Url.toRoute(Url.Search.Keywords, 1), param, handler);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(mContext.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
        }
        String mNewKeyword = KeywordAdapter.getItem(position).getName();
        mSearchBar.setKeyword(mNewKeyword);// 设置EditText控件的内容
        mSearchBar.getEditText().setSelection(mNewKeyword.length());// 将光标移至文字末尾
    }

    private OnClickListener mSearchListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            mSearchBar.getEditText().setFocusable(true);

            if (IntentState && mIntentkeyword.length() >= 1) {
                keywords = mIntentkeyword;
                mSearchBar.setKeyword(keywords);
                mSearchBar.setHint(R.string.search_hint_default);
                mSearchBar.setDeleteVisibility(View.VISIBLE);
                mIntentkeyword = null;
                IntentState = false;
            }

            keywords = mSearchBar.getKeyword();
            if (keywords.length() >= 1) {
                mSearchBar.getEditText().setSelection(keywords.length());// 将光标移至文字末尾
            }

            mSearchBar.getEditText().setCursorVisible(true);

        }
    };

    private OnClickListener mSearchBtnListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager) v.getContext()
                    .getSystemService(mContext.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
            }

            if (IntentState && mIntentkeyword.length() >= 1) {
                keywords = mIntentkeyword;
                mSearchBar.setKeyword(keywords);
                mSearchBar.setHint(R.string.search_hint_default);
                mIntentkeyword = null;
                IntentState = false;
            }

            keywords = mSearchBar.getKeyword();
            if ((keywords.equals("")) || (keywords.length() == 0)) {
                mMatchList.setVisibility(View.GONE);
                Toast.show(mContext, "请输入您要搜索的关键字！");
                return;
            } else {
                mMatchList.setVisibility(View.VISIBLE);
            }
            mSearchBar.setDeleteVisibility(View.VISIBLE);
            if (AppContext.isAilError) {
                AppHelper.StartWebView(SearchActivity.this, AppConfig.TAOCONFIG.SEARCH + keywords);
            } else {
                BaiChuan.showPage(mActivity, keywords, AppConfig.TAOCONFIG.SEARCH + keywords);
            }
        }
    };

    private OnClickListener mDeleteListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            mSearchBar.setKeyword(null);
            mSearchBar.setHint(R.string.search_hint_default);
            mSearchBar.setDeleteVisibility(View.GONE);
            mMatchList.setVisibility(View.GONE);
            mSearchContent.setVisibility(View.VISIBLE);
        }
    };

    private TextWatcher mSearchChangedListener = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() >= 1) {
                keywords = mSearchBar.getKeyword();
                mMatchList.setVisibility(View.VISIBLE);
                mSearchBar.setDeleteVisibility(View.VISIBLE);
                mSearchContent.setVisibility(View.GONE);
                getKeywords();
            } else {
                mMatchList.setVisibility(View.GONE);
                mSearchContent.setVisibility(View.VISIBLE);
            }
        }
    };

    private OnClickListener mBackListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            SearchActivity.this.finish();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl:
            case R.id.network_error_ll:
                getKeywords();
                break;
        }
    }
}
